package com.lz.common.utils.weather;

import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class WeatherService {
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("输出" + WeatherService.getLocalWeather());
    }

    //根据调用者当地获取天气
    public static String getLocalWeather() {
//        https://wttr.in/?format=j1
        String response = HttpUtil.createGet("https://wttr.in/?format=j1")
                .header(Header.CONTENT_TYPE, "application/json")
                .execute()
                .body();

        JsonObject rootObject = JsonParser.parseString(response).getAsJsonObject();

        JsonArray weatherArray = rootObject.getAsJsonArray("weather");

        JsonObject weatherObject = weatherArray.get(0).getAsJsonObject();

        JsonArray hourlyArray = weatherObject.getAsJsonArray("hourly");

        JsonObject hourlyObject = hourlyArray.get(0).getAsJsonObject(); // 注意：这里是第一个元素，不是第24个

        String weatherCodeStr = hourlyObject.get("weatherCode").getAsString();

        int weatherCode = Integer.parseInt(weatherCodeStr);

        return WeatherNumEnum.getChineseByCode(weatherCode);
    }

    //根据调用者当地获取天气
    public static String getWeather(String cityName) {
        String urlString;
        try {
            String encodedFormat = URLEncoder.encode("%C", "UTF-8");
            urlString = "https://wttr.in/" + URLEncoder.encode(cityName, "UTF-8") + "?format=" + encodedFormat + "&lang=zh";
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
//https://wttr.in/%E8%8B%8F%E5%B7%9E?format=%C&lang=zh
        String response = HttpUtil.createGet(urlString)
                .header(Header.CONTENT_TYPE, "application/text")
                .execute()
                .body();
        return response;
    }
}